﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using Fly.PDF.BLL;
using RN.ERP.Web.Utilities;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// PdfDownHandler 的摘要说明
    /// </summary>
    public class PdfDownHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            FuncRoot(context);
        }

        private void FuncRoot(HttpContext context)
        {
            string funcType = context.Request.Params["functype"];
            if(!String.IsNullOrEmpty(funcType))
            {
                funcType=funcType.ToLower();
            }
            switch (funcType)
            {
                case "downloadpdfbyurl": 
                    DownloadPdfByUrl(context); 
                    break;
                case "getcorpinspectpdf": 
                    getCorpInspectPdf(context);
                    break;
                case "kaoheevalpdf":
                    CorpEvalPdf(context);
                    break;
                case "kaohesnappdf":
                    CorpSnapPdf(context);
                    break;
                case "corpsnapeval":
                    CorpSnapEvalPdf(context);
                    break;
                case "getpdf": 
                default:
                GetPdf(context); break;
            }
        }

        private void DownloadPdfByUrl(HttpContext context)
        {
            string url = context.Request.Params["url"];
            string fileName = context.Request.Params["filename"];
            Fly.PDF.BLL.PDFBLL bll = new Fly.PDF.BLL.PDFBLL();
            byte[] content = bll.ConvertHtmlItextToAbcPDF(url);
            Stream fileStream = new MemoryStream(content);
            if (fileStream != null && fileStream.Length > 0)
            {
                DownPdf(fileStream, fileName);
            }
        }

        /// <summary>
        /// 取得pdf文件
        /// </summary>
        /// <param name="context"></param>
        private void getCorpInspectPdf(HttpContext context)
        {
            if (string.IsNullOrEmpty(context.Request.Params["userGuid"]))
            {
                return;
            }
            string userGuid = context.Request.Params["userGuid"].Trim();
            
            string absUrl = context.Request.Url.AbsoluteUri;
            absUrl = absUrl.Substring(0, absUrl.IndexOf("Handlers"));
            string pdfUrl = Path.Combine(absUrl, "KaoHe/AnnualCheckDetail/AnnualCheckExport.aspx?corpUserGuid=" + userGuid);
            Fly.PDF.BLL.PDFBLL bll = new Fly.PDF.BLL.PDFBLL();
            byte[] content = bll.ConvertHtmlUrlToAbcPDF(pdfUrl);
            Stream fileStream = new MemoryStream(content);
            if (fileStream != null && fileStream.Length > 0)
            {
                DownPdf(fileStream, userGuid);
            }
        }

        /// <summary>
        /// 取得pdf文件
        /// </summary>
        /// <param name="context"></param>
        private void GetPdf(HttpContext context)
        {
            if (string.IsNullOrEmpty(context.Request.Params["empGuid"]))
            {
                return;
            }
            string empGuid = context.Request.Params["empGuid"].Trim();

            string absUrl = context.Request.Url.AbsoluteUri;
            absUrl = absUrl.Substring(0, absUrl.IndexOf("Handlers"));
            string pdfUrl = context.Server.HtmlEncode(Path.Combine(absUrl, "Person/ExpertPdf.aspx?empGuid=" + empGuid));
            using (PdfService.PDFServiceClient client = new PdfService.PDFServiceClient())
            {
                Stream fileStream = new MemoryStream(client.GenevatePagingPDFItext(pdfUrl));
                if (fileStream != null && fileStream.Length > 0)
                {
                    DownPdf(fileStream, empGuid);
                }
            }
        }

        /// <summary>
        /// 考核初审评分表pdf
        /// </summary>
        /// <param name="context"></param>
        private void CorpEvalPdf(HttpContext context)
        {
            string areaCode = string.Empty;
            string corpUserGuid = string.Empty;
            string snapGuid = string.Empty;
            string appId = string.Empty;
            int roleId = 0;
            int classId = 0;
            if (!string.IsNullOrEmpty(context.Request.Params["areaCode"]))
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["corpUserGuid"]))
            {
                corpUserGuid = context.Request.Params["corpUserGuid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["snapGuid"]))
            {
                snapGuid = context.Request.Params["snapGuid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["appId"]))
            {
                appId = context.Request.Params["appId"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["classId"]))
            {
                int.TryParse(context.Request.Params["classId"].Trim(), out classId);
            }
            if (!string.IsNullOrEmpty(context.Request.Params["roleId"]))
            {
                int.TryParse(context.Request.Params["roleId"].Trim(), out roleId);
            }
            if (string.IsNullOrEmpty(corpUserGuid) || string.IsNullOrEmpty(snapGuid) || string.IsNullOrEmpty(appId))
            {
                return;
            }
            string url = "Kaohe/CorpEvaluationPdf.aspx?classId=8010&corpUserGuid=" + corpUserGuid + "&snapGuid=" + snapGuid + "&areaCode=" + areaCode + "&appId=" + appId + "&roleId=" + roleId.ToString();
            try
            {
                Fly.PDF.BLL.PDFPageSetting settings = new Fly.PDF.BLL.PDFPageSetting();
                settings.StrPageSize = "0 0 595 840";
                settings.StrRect = "14 14 586 820";
                using (Stream fileStream = new MemoryStream(ConvertHtmlItextToAbcPDF(context,settings, url, snapGuid)))
                {
                    if (fileStream != null && fileStream.Length > 0)
                    {
                        DownPdf(fileStream, snapGuid);
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 考核申请表pdf
        /// </summary>
        /// <param name="context"></param>
        private void CorpSnapPdf(HttpContext context)
        {
            string areaCode = string.Empty;
            string corpUserGuid = string.Empty;
            string snapGuid = string.Empty;
            if (!string.IsNullOrEmpty(context.Request.Params["areaCode"]))
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["corpUserGuid"]))
            {
                corpUserGuid = context.Request.Params["corpUserGuid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["snapGuid"]))
            {
                snapGuid = context.Request.Params["snapGuid"];
            }

            if (string.IsNullOrEmpty(corpUserGuid) || string.IsNullOrEmpty(snapGuid))
            {
                return;
            }
            string url = "Kaohe/CorpSnapPdf.aspx?corpUserGuid=" + corpUserGuid + "&snapGuid=" + snapGuid + "&areaCode=" + areaCode;
            try
            {
                Fly.PDF.BLL.PDFPageSetting settings = new Fly.PDF.BLL.PDFPageSetting();
                settings.StrPageSize = "0 0 595 840";
                settings.StrRect = "20 20 586 810";
                using (Stream fileStream = new MemoryStream(ConvertHtmlUrlToAbcPDF(context, settings, url)))
                {
                    if (fileStream != null && fileStream.Length > 0)
                    {
                        DownPdf(fileStream, snapGuid);
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 主管信用评价实际初审意见汇总表pdf
        /// </summary>
        /// <param name="context"></param>
        private void CorpSnapEvalPdf(HttpContext context)
        {
            string areaCode = string.Empty;
            string appId = string.Empty;
            DateTime startDate=DateTime.Parse(DateTime.Now.Year.ToString() + "-1" + "-1");
            
            int roleId=0;
            if (!string.IsNullOrEmpty(context.Request.Params["areaCode"]))
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["appId"]))
            {
                appId = context.Request.Params["appId"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["startDate"]))
            {
                DateTime.TryParse(context.Request.Params["startDate"].Trim(), out startDate);
            }
            DateTime endDate= startDate.AddYears(1);
            if (!string.IsNullOrEmpty(context.Request.Params["endDate"]))
            {
               DateTime.TryParse(context.Request.Params["endDate"].Trim(), out endDate);
            }
            if (!string.IsNullOrEmpty(context.Request.Params["roleId"]))
            {
                int.TryParse(context.Request.Params["roleId"].Trim(), out roleId);
            }
            int corpRoleId = 0;
            int cityRoleId = 0;
            if (KaoheRoleIDHelp.CityRoleId==roleId.ToString() || KaoheRoleIDHelp.ProvinceRoleId==roleId.ToString())
            {
                ////市级角色
                int.TryParse(KaoheRoleIDHelp.CityRoleId, out cityRoleId);
                ////企业角色
                int.TryParse(KaoheRoleIDHelp.CorpRoleId, out corpRoleId);
            }
            string url = "Kaohe/CorpSnapEvalPdf.aspx?corpRoleId=" + corpRoleId + "&cityRoleId=" + cityRoleId + "&areaCode=" + areaCode + "&appId=" + appId + "&startDate=" + startDate + "&endDate=" + endDate;
            try
            {
                Fly.PDF.BLL.PDFPageSetting settings = new Fly.PDF.BLL.PDFPageSetting();
                settings.StrPageSize = "0 0 840 595";
                settings.StrRect = "20 20 810 586";
                using (Stream fileStream = new MemoryStream(ConvertHtmlUrlToAbcPDF(context, settings, url)))
                {
                    if (fileStream != null && fileStream.Length > 0)
                    {
                        DownPdf(fileStream, Guid.NewGuid().ToString());
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 返回Pdf流
        /// </summary>
        /// <param name="context"></param>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        private byte[] ConvertHtmlItextToAbcPDF(HttpContext context, Fly.PDF.BLL.PDFPageSetting settings,string url, string fileName)
        {
            try
            {
                string absUrl = context.Request.Url.AbsoluteUri;
                absUrl = absUrl.Substring(0, absUrl.IndexOf("Handlers"));
                string pdfUrl = Path.Combine(absUrl, url);
                Fly.PDF.BLL.PDFBLL bll = new Fly.PDF.BLL.PDFBLL(settings);
                return bll.ConvertHtmlItextToAbcPDF(pdfUrl);
              
            }
            catch { }
            return null;
        }

        /// <summary>
        /// 直接通过url返回Pdf流
        /// </summary>
        /// <param name="context"></param>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        private byte[] ConvertHtmlUrlToAbcPDF(HttpContext context, Fly.PDF.BLL.PDFPageSetting settings, string url)
        {
            try
            {
                string absUrl = context.Request.Url.AbsoluteUri;
                absUrl = absUrl.Substring(0, absUrl.IndexOf("Handlers"));
                string pdfUrl = Path.Combine(absUrl, url);
                Fly.PDF.BLL.PDFBLL bll = new Fly.PDF.BLL.PDFBLL(settings);
                return bll.ConvertHtmlUrlToAbcPDF(pdfUrl);

            }
            catch { }
            return null;
        }

        /// <summary>
        /// 下载PDF
        /// </summary>
        /// <param name="file"></param>
        public static void DownPdf(Stream fs, string fileName)
        {
            if (fs == null || fs.Length == 0)
            {
                return;
            }

            fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;FileName=" + fileName+".pdf");
            HttpContext.Current.Response.AddHeader("Content-Length", fs.Length.ToString());
            HttpContext.Current.Response.ContentType = "application/pdf";
            
            long fileLength = fs.Length;
            int size = 10240;
            byte[] readData = new byte[size];
            if (size > fileLength)
                size = Convert.ToInt32(fileLength);
            long fPos = 0;
            bool isEnd = false;
            while (!isEnd)
            {
                if ((fPos + size) >= fileLength)
                {
                    size = Convert.ToInt32(fileLength - fPos);
                    isEnd = true;
                }
                readData = new byte[size];
                fs.Position = fPos;
                fs.Read(readData, 0, size);
                HttpContext.Current.Response.BinaryWrite(readData);
                HttpContext.Current.Response.OutputStream.Flush();
                fPos += size;
            }
            fs.Close();
            HttpContext.Current.Response.OutputStream.Close();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
